const {shell} = require('electron');
var remote = require('electron').remote;
var path = remote.require('path');
const {dialog} = require('electron').remote
const unusedFilename = remote.require('unused-filename');
var app = remote.app;
var fs = require('fs');

var IMService = require('../lib/im.js');
var FileCommand = require('./file_command.js');
var P2PFileSession = require('./p2pfile_session.js');
var {P2PFileSender, P2PFileReceiver} = require('./p2p_file.js');


var p2pFileSender;
var p2pFileReceiver;
var p2pFileSession;
var im;
var uid;
var peer;
var peerName;
var peerAvatar;
var token;
var channelID;
var isCaller;
var filePath;
var fileName;
var fileSize;
var tmpFilePath;//下载过程中的临时文件存储路径
var fileMD5;

var duration = 0;
var lastSize = 0;

var durationView;
var progress;
var bitrateDiv;

//上次获取stats的时间戳
var getStatsTimestmap = 0;

//1 second
var heartbeatTimer = 0;
var showExitPrompt = true;


var c = window.close;
window.close = function() {
    showExitPrompt = false;
    c.call(this);
}

function getURLParameter(name, search) {
    search = search || location.search
    var param = search.match(
        RegExp(name + '=' + '(.+?)(&|$)'))
    return param ? decodeURIComponent(param[1]) : undefined;
}

function onHangUp() {
    console.log("on hangup");
    var message = isCaller ? "停止发送文件？" : "停止接受文件？";
    var options = {
        message:message,
        buttons:["确定", "取消"],
        defaultId:0,
        cancelId:1
    };
    var self = this;
    var win = remote.getCurrentWindow();
    dialog.showMessageBox(win, options, function(response) {
        if (response == 1) {
            return;
        }

        if (p2pFileSession) {
            p2pFileSession.hangUp();
            p2pFileSession = null;
        }

        document.getElementById('hangup').style.display = 'none';

        window.close();
    });
}

function onOpen() {
    shell.openItem(filePath);
}

function onOpenDir() {
    shell.showItemInFolder(filePath);
}


//p2pfile session callback
function onConnected() {
    console.log("on connected");
    P2PFileSession.prototype.onConnected.call(this);

    if (isCaller) {
        p2pFileSender = new P2PFileSender(filePath, fileSize);
        p2pFileSender.im = im;
        p2pFileSender.uid = uid;
        p2pFileSender.token = token;
        p2pFileSender.peer = peer;
        p2pFileSender.channelID = channelID;

        p2pFileSender.onsended = function(sended) {
            console.log("sended:", sended, fileSize);
            progress.value = sended;
        }

        p2pFileSender.oncompleted = function(fileMD5) {
            window.fileMD5 = fileMD5;
            p2pFileSession.fileMD5 = fileMD5;
        }

        p2pFileSender.createConnection();
    } else {
        const dir = app.getPath('downloads');
        tmpFilePath = unusedFilename.sync(path.join(dir, fileName + '.download'));

        p2pFileReceiver = new P2PFileReceiver(tmpFilePath, fileSize);
        p2pFileReceiver.im = im;
        p2pFileReceiver.uid = uid;
        p2pFileReceiver.token = token;
        p2pFileReceiver.peer = peer;
        p2pFileReceiver.channelID = channelID;

        p2pFileReceiver.oncompleted = function(fileMD5) {
            window.fileMD5 = fileMD5;
            p2pFileSession.complete();

        }
        p2pFileReceiver.onreceived = function(received) {
            console.log("received:", received, fileSize);
            progress.value = received;
        }

        p2pFileReceiver.createConnection();
    }

    heartbeatTimer = setInterval(heartbeat, 1000);

    if (isCaller) {
        document.getElementById('bitrate').innerHTML = "发送中...";
    } else {
        document.getElementById('bitrate').innerHTML = "接受中...";
    }
}


function onRemoteHangUp() {
    P2PFileSession.prototype.onRemoteHangUp.call(this);

    p2pFileSession = null;

    if (heartbeatTimer) {
        clearInterval(heartbeatTimer);
    }

    if (isCaller) {
        alert("对方中止了接受文件");
    } else {
        alert("对方中止了发送文件");
    }

    window.close();
}
function onRemoteRefuse() {
    P2PFileSession.prototype.onRemoteRefuse.call(this);
    p2pFileSession = null;

    if (heartbeatTimer) {
        clearInterval(heartbeatTimer);
    }
    alert("对方拒绝了文件");
    window.close();
}

function onDialTimeout() {
    P2PFileSession.prototype.onDialTimeout.call(this);
    p2pFileSession = null;
    alert("对方不在线，无法发送文件");
    window.close();
}

function onOffline() {
    P2PFileSession.prototype.onOffline.call(this);
    p2pFileSession = null;
    alert("对方不在线，无法发送文件");
    window.close();
}

function onCompleted() {
    console.log("on completed");
    if (heartbeatTimer) {
        clearInterval(heartbeatTimer);
    }
    showExitPrompt = false;

    if (isCaller) {
        p2pFileSender.closeDataChannels();
        document.getElementById('progress').style.display = 'none';
        document.getElementById('hangup').style.display = 'none';
        bitrateDiv.style.display = "发送完成";

        console.log("send completed");
        //todo close window
        alert("发送完成");
        window.close();
    } else {
        document.getElementById('progress').style.display = 'none';
        document.getElementById('hangup').style.display = 'none';
        bitrateDiv.style.display = "none";

        console.log("check file md5:", p2pFileSession.fileMD5, fileMD5);
        if (!p2pFileSession.fileMD5) {
            alert("文件校验失败");
            return;
        }

        if (p2pFileSession.fileMD5 != fileMD5) {
            alert("文件校验失败");
            return;
        }

        const dir = app.getPath('downloads');
        filePath = unusedFilename.sync(path.join(dir, fileName));
        fs.renameSync(tmpFilePath, filePath);
        console.log("rename:", tmpFilePath, filePath);


        document.getElementById('open').style.display = 'inline';
        document.getElementById('open-dir').style.display = 'inline';
    }
}

function formatDuration(duration) {
    var m = Math.floor(duration/60);
    var s = duration%60;
    return (m < 10 ? '0' : '') + m + ":" + (s < 10 ? '0' : '') + s;
}

function heartbeat() {
    duration += 1;

    durationView.innerHTML = formatDuration(duration);

    if (p2pFileSender) {
        var bitrate = (p2pFileSender.sendedSize - lastSize);
        if (bitrate < 1024*2) {
            bitrateDiv.innerHTML = bitrate + 'B/s';
        } else if (bitrate < 1024*1024) {
            bitrateDiv.innerHTML = (bitrate/1024).toFixed(1) + 'KB/s';
        } else {
            bitrateDiv.innerHTML = (bitrate/(1024*1024)).toFixed(1) + 'MB/s';
        }

        lastSize = p2pFileSender.sendedSize;
    } else if (p2pFileReceiver) {
        var bitrate = (p2pFileReceiver.receivedSize - lastSize);
        if (bitrate < 1024*2) {
            bitrateDiv.innerHTML = bitrate + 'B/s';
        } else if (bitrate < 1024*1024) {
            bitrateDiv.innerHTML = (bitrate/1024).toFixed(1) + 'KB/s';
        } else {
            bitrateDiv.innerHTML = (bitrate/(1024*1024)).toFixed(1) + 'MB/s';
        }
        lastSize = p2pFileReceiver.receivedSize;
    }

}

var observer = {
    handleRTMessage:function(msg) {
        if (msg.receiver != uid) {
            return;
        }

        var rtObj = JSON.parse(msg.content);
        if (rtObj.p2p) {
            if (channelID != rtObj.p2p.channel_id) {
                return;
            }
            if (p2pFileSender) {
                p2pFileSender.handleP2PMessage(rtObj.p2p);
            } else if (p2pFileReceiver) {
                p2pFileReceiver.handleP2PMessage(rtObj.p2p);
            }
        } else if (rtObj.file) {
            var obj = rtObj.file;
            if (channelID != obj.channel_id) {
                return;
            }
            if (p2pFileSession) {
                p2pFileSession.handleFileMessage(obj, msg.sender);
            }
        }
    },

    onConnectState: function(state) {
        if (state == IMService.STATE_CONNECTED) {
            console.log("im connected");
        } else if (state == IMService.STATE_CONNECTING) {
            console.log("im connecting");
        } else if (state == IMService.STATE_CONNECTFAIL) {
            console.log("im connect fail");
        } else if (state == IMService.STATE_UNCONNECTED) {
            console.log("im unconnected");
        }
    }
};


function createSession(im, uid, peer, token, channelID, isCaller) {
    var p2pFileSession = new P2PFileSession(im);

    p2pFileSession.onConnected = onConnected;
    p2pFileSession.onRemoteHangUp = onRemoteHangUp;
    p2pFileSession.onDialTimeout = onDialTimeout;
    p2pFileSession.onRemoteRefuse = onRemoteRefuse;
    p2pFileSession.onOffline = onOffline;
    p2pFileSession.onCompleted = onCompleted;
    p2pFileSession.uid = uid;
    p2pFileSession.peer = peer;
    p2pFileSession.isCaller = isCaller;
    p2pFileSession.channelID = channelID;
    p2pFileSession.fileName = fileName;
    p2pFileSession.fileSize = fileSize;
    return p2pFileSession;
}

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("location.search:", location.search);
    uid = getURLParameter("uid");
    peer = getURLParameter("peer");
    peerName = getURLParameter("name");
    peerAvatar = getURLParameter("avatar");
    token = getURLParameter("token");
    channelID = getURLParameter("channel");
    filePath = getURLParameter('file_path');
    fileName = getURLParameter('file_name');
    fileSize = getURLParameter('file_size');
    isCaller = getURLParameter("is_caller");

    if (isNaN(parseInt(isCaller))) {
        isCaller = isCaller == 'true';
    } else {
        isCaller = parseInt(isCaller);
    }
    uid = parseInt(uid);
    peer = parseInt(peer);
    fileSize = parseInt(fileSize);
    if (!token) {
        return;
    }

    console.log("token:", token, "uid:", uid, "peer:", peer, "name:", peerName, "avatar:", peerAvatar);
    console.log("file path:", filePath, "fileName:", fileName, "file size:", fileSize);

    progress = document.querySelector('progress#progress');
    progress.max = fileSize;

    document.getElementById('title').textContent = fileName;
    durationView = document.getElementById('duration');
    bitrateDiv = document.querySelector('div#bitrate');
    bitrateDiv.innerHTML = "连接中...";

    im = new IMService();
    im.isSync = false;//不接受im消息,只接受rt消息
    im.observer = observer;
    im.accessToken = token;
    im.start();

    if (isCaller) {
        p2pFileSession = createSession(im, uid, peer, token, channelID, true);
        p2pFileSession.dial();
    } else {
        p2pFileSession = createSession(im, uid, peer, token, channelID, false);
    }
});



window.onbeforeunload = function(e) {
    if (showExitPrompt) {
        var message = isCaller ? "停止发送文件？" : "停止接受文件？";
        var options = {
            message: message,
            buttons: ["确定", "取消"],
            defaultId: 0,
            cancelId: 1
        };
        var self = this;
        var win = remote.getCurrentWindow();
        dialog.showMessageBox(win, options, function(response) {
            if (response == 1) {
                return;
            }
            if (p2pFileSession) {
                p2pFileSession.hangUp();
                p2pFileSession = null;
            }
            window.close();
        });
        e.returnValue = false;
    }

};
